package com.hns.frame.security;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.util.ResponseUtil;
import com.hns.tool.pub.PubUtil;


/**
 * 异常处理
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class AppExceptionHandler implements HandlerExceptionResolver {  
    static final Logger logger = LoggerFactory.getLogger(AppExceptionHandler.class);
    /**
     * {@inheritDoc}
     * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     * @创建日期:2014-5-13
     * @功能说明：异常处理
     */
    @Override  
    public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object object, Exception exception) {
        if(exception instanceof BusinessException){
            //自定义异常返回json格式数据
            String message = exception.getMessage();
            String msgType = ((BusinessException) exception).getMsgType();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", false);
            if(PubUtil.isEmpty(msgType)){
                message = "系统异常，请联系管理员！";
            }else{
                map.put("msg", message);
                map.put("msgType", msgType);
            }
            logger.error(exception.getMessage());
            ResponseUtil.responseJSON(map, response);
        }else{
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", false);
            map.put("msg", "系统异常，请联系管理员！");
            map.put("msgType", MsgType.ERROR.getFlag());
            StringWriter sw=new StringWriter();  
            PrintWriter pw=new PrintWriter(sw);  
            exception.printStackTrace(pw); 
            logger.error(sw.toString());
            ResponseUtil.responseJSON(map, response);
        }
        return null;  
    }  
  
} 